package cn.cqone.crm.service.impl;

import cn.cqone.crm.domain.Menu;
import cn.cqone.crm.domain.Permission;
import cn.cqone.crm.mapper.MenuMapper;
import cn.cqone.crm.query.MenuQuery;
import cn.cqone.crm.service.MenuService;
import cn.cqone.crm.service.PermissionService;
import cn.cqone.crm.utils.PageList;
import javafx.beans.binding.When;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
@Transactional
public class MenuServiceImpl extends BaseServiceImpl<Menu,Long,MenuQuery> implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionService permissionService;

    @Override
    public List<Menu> findMenu() {
        List<Menu> list = menuMapper.findMenu();
        list.forEach(l -> {
            List<Menu> menuList = menuMapper.findByParentId(l.getId());
            l.setChildren(menuList);
        });

        return list;
    }

    //根据用户的id查询用户拥有的菜单权限
    @Override
    public List<Menu> findMenuByEmployeeId(Long employeeId) {
        //查询出所有菜单
        List<Menu> list = findMenu();
        //根据用户id查询出拥有的权限
        List<Permission> permission = permissionService.findPermissionByEmployeeId(employeeId);
        Iterator<Menu> i = list.iterator();
        //定义一个数组来装菜单id
        List<Long> e =new ArrayList<>();
        //循环用户的所有权限
        permission.forEach(p->{
            //把用户拥有的所有菜单id存入一个数组
           e.add(p.getMenu().getId());
        });
        //循环所有父菜单，内带子菜单
        while (i.hasNext()) {
            Menu next = i.next();
            List<Menu> children = next.getChildren();
            Iterator<Menu> j = children.iterator();
            //循环所有子菜单
            while (j.hasNext()){
                Menu menu = j.next();
                if(!e.contains(menu.getId())){
                    j.remove();
                }
            }
            //如果父菜单一个子菜单都没有，就删除父菜单
            if(children.isEmpty()){
                i.remove();
            }
        }

        return list;
    }

}
